<?php

/**
 * theme actions.
 *
 * @package    jiazhang
 * @subpackage theme
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class themeActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
     $this->getResponse()->setTitle('话题 - 壹童学');
     $dql = Doctrine::getTable('TalkTheme')->createQuery()->andWhere('display = 1')->orderBy('created_at desc');
     $page = $request->getParameter('page',1);
     $this->pager = new sfDoctrinePager('TalkTheme',20);
     $this->pager->setQuery($dql);
     $this->pager->setPage($page);
     $this->pager->init();
  }
  
  public function executeShow(sfWebRequest $request){
      $this->forward404Unless($this->theme = Doctrine::getTable('TalkTheme')->findOneById($id = $request->getParameter('id',0)));
      $this->getResponse()->setTitle($this->theme->getTitle().' - 话题详情 - 壹童学');
      $this->theme->getAttr()->addReadNum();
      $this->new_theme = Doctrine::getTable('TalkTheme')->createQuery()->where('group_id = ?',$this->theme->getGroup()->getId())->andWhere('display = 1')->andWhere('has_cover = 1')->orderBy('created_at desc')->fetchOne();
      
      if($this->new_theme){
         $this->themes = Doctrine::getTable('TalkTheme')->createQuery()->where('group_id = ?',$this->theme->getGroup()->getId())->andWhere('display = 1')->andWhere('id <> ?',$this->new_theme['id'])->orderBy('created_at desc')->limit(3)->execute(); 
      }else{
          $this->themes = Doctrine::getTable('TalkTheme')->createQuery()->where('group_id = ?',$this->theme->getGroup()->getId())->andWhere('display = 1')->orderBy('created_at desc')->limit(3)->execute();
      }
  }
  
    public function executeCreate_comment(sfWebRequest $request){
        if($request->isMethod('POST')){
          $this->forward404Unless($theme = Doctrine::getTable('TalkTheme')->findOneById( $theme_id = $request->getParameter('theme_id',0)));  
          $content = trim($request->getParameter('content',''));
          $user_id = $this->getUser()->getAttribute('user_id',0);
          
          if(strlen($content) == 0){
            $this->getUser()->setFlash('error','评论内容不能为空！');
            $this->redirect('theme/show?id='.$theme_id);
          }
          
          $theme_comment= new ThemeComment();
          $theme_comment->setUserId($user_id)->setThemeId($theme_id)->setContent($content)->save();
          $theme->getAttr()->addCommentNum();
          $this->getUser()->setFlash('success','评论发布成功！');
          $this->redirect('theme/show?id='.$theme_id);
        }
    }
  
  
   public function executeRecommend_group(sfWebRequest $request){
       $group_ids = Doctrine::getTable('GroupUser')->createQuery()->where('user_id = ?',$this->getUser()->getAttribute('user_id',0))->execute()->toKeyValueArray('group_id', 'group_id');
       $rand_group_ids = Doctrine::getTable('Jgroup')->createQuery()->where('display = 1')->andWhere('recommend = 1')->andWhereNotIn('id',$group_ids)->orderBy('created_at desc')->execute()->toKeyValueArray('id', 'id');

       if(count($rand_group_ids) > 5){
         $next_group_id = array_rand($rand_group_ids,5);
         $this->groups =  Doctrine::getTable('Jgroup')->createQuery()->where('display = 1')->andWhere('recommend = 1')->andWhereIn('id',$next_group_id)->orderBy('created_at desc')->execute();
       }else{
          $this->groups =  Doctrine::getTable('Jgroup')->createQuery()->where('display = 1')->andWhere('recommend = 1')->andWhereIn('id',$rand_group_ids)->orderBy('created_at desc')->execute();
       }
       
   }
    
  public function executeGroup(sfWebRequest $request)
  {
      $this->forward404Unless($this->group_info = Doctrine::getTable('Jgroup')->findOneById($this->id = $request->getParameter('id',0)));
      $this->getResponse()->setTitle($this->group_info->getName().' - 小组话题列表 - 壹童学');
      $recommend = (int)$request->getParameter('recommend',0);
      
      if($recommend == 1){
          $dql = Doctrine::getTable('TalkTheme')->createQuery()->where('group_id = ?',$this->id)->andWhere('display = 1')->andWhere('recommend = 1')->orderBy('created_at desc');
      }else{
          $dql = Doctrine::getTable('TalkTheme')->createQuery()->where('group_id = ?',$this->id)->andWhere('display = 1')->orderBy('created_at desc');
      }
      
     $page = $request->getParameter('page',1);
     $this->pager = new sfDoctrinePager('TalkTheme',20);
     $this->pager->setQuery($dql);
     $this->pager->setPage($page);
     $this->pager->init();
      
  }
  
  public function executeAdd(sfWebRequest $request)
  {
      $this->forward404Unless($this->group_info = Doctrine::getTable('Jgroup')->findOneById($this->id = $request->getParameter('group_id',0)));
      $this->getResponse()->setTitle('发布话题 - 壹童学');
      
      if(!$this->group_info->hasUserById($this->getUser()->getAttribute('user_id'))){
          $this->getUser()->setFlash('error','请先加入小组');
          $this->redirect('theme/group?id='.$this->id);
      }
  }
  
  
  public function executeCreate(sfWebRequest $request)
  {
      if($request->isMethod('POST')){
          $this->forward404Unless($this->group = Doctrine::getTable('Jgroup')->findOneById($group_id = $request->getParameter('group_id',0)));
          $user_id = $this->getUser()->getAttribute('user_id',0);
          
          if(!$this->group->hasUserById($user_id)){
                $this->getUser()->setFlash('error','请先加入小组');
                $this->redirect('theme/group?id='.$group_id);
          }

          $title = $request->getParameter('title','');
          $content = $request->getParameter('content','');
          $images = $request->getParameter('images',array());
        
          $theme = new TalkTheme();
          $theme->setTitle($title)->setContent(nl2br($content))->setUserId($user_id)->setGroupId($group_id)->save();
          $theme->createAttr();
          $this->group->addThemeNum();
          
          if(count($images) >= 1){
              $theme->setHasCover(1)->setCover($images[1])->save();
              
              foreach($images as $img_url){
                  $theme_img = new ThemeImage();
                  $theme_img->setImageUrl($img_url)->setThemeId($theme->getId())->save();
              }
          }
          
          $this->getUser()->setFlash('success','话题发布成功！');
          $this->redirect('theme/group?id='.$group_id);
      }
  }
  
  //@tudo:是否再增加一个表记录当前用户总共上传了多少图或者做个临时数据定期清除
  public function executeImages(sfWebRequest $request){
       sfConfig::set('sf_web_debug',false);

      if($request->isMethod('POST')){
          $file = $request->getFiles('Filedata');
          
          if($file['error'] == 4){
              exit();
          }
          
          $file_name = $file['name'];
          $file_ext_tmp = explode('.', $file_name);
          $file_ext = $file_ext_tmp[count($file_ext_tmp)-1];
          $allow_file_type = array('jpg','bmp','png','gif','jpeg');
          
          if(in_array($file_ext, $allow_file_type)){
             $year = date('Y',time());
             $month = date('m',time());
             $day = date('d',time());
             $save_file_name = $year.'_'.$month.'_'.$day.'_'.substr(md5(time()+rand(0,999)),25).'.'.$file_ext;
             $upyun_save_path = '/theme/tmp/'.$year.'/'.$month.'/'.$day.'/'.$save_file_name;
             $upyun = new UpYun(sfConfig::get('app_upyun_space'),sfConfig::get('app_upyun_user') , sfConfig::get('app_upyun_pwd'));
             
             try {
                $fh = fopen($file['tmp_name'], 'rb');
                $rsp = $upyun->writeFile($upyun_save_path, $fh, True);   // 上传图片，自动创建目录
                fclose($fh);
                $image_url=  sfConfig::get('app_img_url').$upyun_save_path;
                $json = new Services_JSON();
                $return_data = array('error' => 0, 'url' => $image_url);
                return $this->renderText($json->encode($return_data));
                exit();
            } catch(Exception $e) {
                echo $e->getCode();
                echo $e->getMessage();
            }
            
          }else{
              $return_data = array('error' => 1, 'url' => '文件类型错误！');
              //error 文件类型错误
              $json = new Services_JSON();
              return $this->renderText($json->encode($return_data));
              exit();
          }
      }
  }
  
  public function executeAttention(sfWebRequest $request){
      if($request->isXmlHttpRequest()){
          $user_id = $this->getUser()->getAttribute('user_id',0);
          $group_id = (int)$request->getParameter('group_id',0);
          $return_msg = array('error'=>0,'msg'=>'');
          
          if(!$this->getUser()->isAuthenticated()){
              $return_msg['error'] = 1;
              $return_msg['msg'] = '请先登入！';
              return $this->renderText(json_encode($return_msg));
          }
          
          $is_attention = Doctrine::getTable('GroupUser')->groupHasUserById($group_id,$user_id);
          
          if($is_attention != 0){ 
              $return_msg['error'] = 1;
              $return_msg['msg'] = '您已经加入了该小组！';
              return $this->renderText(json_encode($return_msg));
          }
          
          $group = Doctrine::getTable('Jgroup')->findOneById($group_id);
          if(!$group) return $this->renderText(json_encode($return_msg));
          
          $group_user = new GroupUser();
          $group_user->setUserId($user_id)->setGroupId($group_id)->save();
          $group->addPeopleNum();
          
          $return_msg['error'] = 0;
          $return_msg['msg'] = '您已经成功加入了该小组！';
          $return_msg['data'] = array();
          $return_msg['data']['people_num'] = $group->getPeopleNum();
          $return_msg['data']['people'] = Doctrine::getTable('GroupUser')->getPersonCoverToArray($group_id);
          
          return $this->renderText(json_encode($return_msg));
      }
  }
  
  public function executeUnattention(sfWebRequest $request){
      if($request->isXmlHttpRequest()){
          $user_id = $this->getUser()->getAttribute('user_id',0);
          $group_id = (int)$request->getParameter('group_id',0);
          $return_msg = array('error'=>0,'msg'=>'');
          
          if(!$this->getUser()->isAuthenticated()){
              $return_msg['error'] = 1;
              $return_msg['msg'] = '请先登入！';
              return $this->renderText(json_encode($return_msg));
          }
          
          $group_user = Doctrine::getTable('GroupUser')->groupUserById($group_id,$user_id);
       
          if(count($group_user) == 0){ 
              $return_msg['error'] = 1;
              $return_msg['msg'] = '您还没有加入该小组哦！';
              return $this->renderText(json_encode($return_msg));
          }
          
          $group = Doctrine::getTable('Jgroup')->findOneById($group_id);
          if(!$group) return $this->renderText(json_encode($return_msg));
          
          $group_user->delete();
          $group->decreasePeopleNum();
          
          $return_msg['error'] = 0;
          $return_msg['msg'] = '您已经退出了该小组！';
          $return_msg['data'] = array();
          $return_msg['data']['people_num'] = $group->getPeopleNum();
          $return_msg['data']['people'] = Doctrine::getTable('GroupUser')->getPersonCoverToArray($group_id);
          
          return $this->renderText(json_encode($return_msg));
      }
  }
}
